<template>
  <div class="chat-detail-container">
    <div class="content" v-if="chatStore.currentSessionId">
      <div class="header">
        <span class="no-drag" @click="handleOpenDrawer">{{ chatStore.currentChat.contactName }}</span>
        <div class="more-btn no-drag">
          <el-icon @click="handleOpenDrawer">
            <MoreFilled />
          </el-icon>
        </div>
      </div>
      <div class="main-container" ref="mainContainerRef">
        <div tabindex="0" ref="drawerRef" @focusout="handleFocusOut"
          :class="['drawer', drawerShow ? 'drawer-active' : 'drawer-dis']">
          <div class="drawer-inner">
            <ul class="drawer-header">
              <li v-for="item in 10">
                <avatar avatar="https://img.tuxiangyan.com/zb_users/upload/2023/02/202302091675904133489339.jpg">
                </avatar>
                <span class="title">A-</span>
              </li>
              <li>
                <add></add>
                <span class="title">添加</span>
              </li>
            </ul>

            <ul class="drawer-body">
              <li>
                <span>查找聊天内容</span>
                <el-icon>
                  <ArrowRight />
                </el-icon>
              </li>
              <li>
                <span>消息免打扰</span>
                <el-switch v-model="userConfig.daRao" class="ml-2" size="small" />
              </li>
              <li>
                <span>置顶聊天</span>
                <el-switch v-model="userConfig.top" class="ml-2" size="small" />
              </li>
              <li class="clear">
                <span>清空聊天记录</span>
              </li>
            </ul>

          </div>
        </div>



        <div class="message-list-wrapper">
          <el-scrollbar height="100%" class="no-drag" ref="messageListContainer">
            <div class="chat-message-list-container" ref="messageListContent">
              <ul class="chat-message-list">
                <li v-for="(item, index) in chatStore.messageList.slice().reverse()" :key="item.messageId">
                  <message-item :showTime="shouldShowTime(chatStore.messageList.slice().reverse(), index)"
                    :message="item"></message-item>
                </li>
              </ul>
            </div>
          </el-scrollbar>
        </div>

        <div class="resize-handle-horizontal no-drag" @mousedown="startResize"></div>

        <div class="message-input-container" :style="{ height: inputHeight + 'px' }">
          <message-input>
          </message-input>
        </div>

      </div>

    </div>
    <empty v-else></empty>
  </div>
</template>

<script setup>
import { useChatStore } from '@/stores/chat'
import { MoreFilled, ArrowRight } from '@element-plus/icons-vue'
import empty from '@/components/empty/index.vue'
import messageInput from '@/components/messageInput/index.vue'
import messageItem from '@/views/chat/detail/messageItem/index.vue'
import avatar from '@/components/chat/chatAvatar/index.vue'
import add from '@/components/user/add/index.vue'

import { nextTick, ref, onMounted, onUnmounted, watch, computed } from 'vue'


const userConfig = ref({})

const drawerShow = ref(false)
const drawerRef = ref(null)
const messageListContainer = ref(null)
const messageListContent = ref(null)

const isUserClick = ref(false)

const chatStore = useChatStore()




function shouldShowTime(list, index) {
  const TIME_INTERVAL = 5 * 60 * 1000
  if (!Array.isArray(list) || list.length === 0 || index === 0) return true

  const cur = toMs(list[index]?.createTime)
  const prev = toMs(list[index - 1]?.createTime)
  if (!cur || !prev) return true
  return cur - prev >= TIME_INTERVAL
}


function toMs(t) {
  if (t == null) return 0
  if (typeof t === 'number') {
    // 如果是秒级（10位），转成毫秒
    return t < 1e12 ? t * 1000 : t
  }
  // 尝试数字字符串
  const n = Number(t)
  if (!Number.isNaN(n)) return n < 1e12 ? n * 1000 : n
  const parsed = Date.parse(t)
  return Number.isFinite(parsed) ? parsed : 0
}




// 拖拽调整大小配置
const inputHeight = ref(200) // 输入框高度，单位px
const isResizing = ref(false) // 是否正在拖拽调整大小

// 高度限制配置（可以根据需要调整这些值）
const MIN_INPUT_HEIGHT = 200   // 输入框最小高度，保证能输入文字
const MAX_INPUT_HEIGHT = 400  // 输入框最大高度，避免占用太多空间

const startResize = (e) => {
  isResizing.value = true

  // 记录拖拽开始时的鼠标位置和当前输入框高度
  const startY = e.clientY
  const startInputHeight = inputHeight.value

  const handleMouseMove = (e) => {
    // 计算鼠标移动的距离
    const deltaY = e.clientY - startY

    // 计算新的输入框高度：向上拖拽减少输入框高度，向下拖拽增加输入框高度
    let newInputHeight = startInputHeight - deltaY

    // 应用高度限制，确保输入框在合理范围内
    newInputHeight = Math.max(MIN_INPUT_HEIGHT, Math.min(MAX_INPUT_HEIGHT, newInputHeight))

    // 更新输入框高度，消息列表会自动填充剩余空间
    inputHeight.value = newInputHeight
  }

  const handleMouseUp = () => {
    // 结束拖拽，清理事件监听器和样式
    isResizing.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
    document.body.style.cursor = ''
    document.body.style.userSelect = ''
  }

  // 添加全局事件监听器，设置拖拽样式
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
  document.body.style.cursor = 'row-resize' // 显示调整大小光标
  document.body.style.userSelect = 'none'   // 禁止文字选择
}

// 自动滚动到底部
const scrollToBottom = () => {
  if (messageListContainer.value) {
    nextTick(() => {
      console.log(messageListContent.value.clientHeight)
      messageListContainer.value.setScrollTop(messageListContent.value.clientHeight)
    })
  }
}

// 监听消息列表变化，自动滚动到底部
watch(() => chatStore.messageList.length, () => {
  scrollToBottom()
})

// 组件挂载时滚动到底部
onMounted(() => {
  scrollToBottom()
})

// 清理事件监听器
onUnmounted(() => {
  // 清理可能残留的事件监听器
  document.body.style.cursor = ''
  document.body.style.userSelect = ''
})


// 失焦时隐藏
const handleFocusOut = () => {
  drawerShow.value = false
  isUserClick.value = true
}

// 点击弹出/关闭
const handleOpenDrawer = async () => {
  if (isUserClick.value) {
    isUserClick.value = false
    return
  }
  drawerShow.value = !drawerShow.value
  if (drawerShow.value) {

    await nextTick()
    // 获得焦点
    drawerRef.value.focus()
  }


}

defineExpose({
  scrollToBottom
})

</script>



<style scoped lang="less">
.chat-detail-container {
  width: 100%;
  height: 100%;
  //background-color: red;
  display: flex;
  align-items: center;
  flex-direction: column;
  background-color: rgb(237, 237, 237);
  color: black;


  .content {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    user-select: none;

    .header {
      width: 100%;
      color: black;
      height: 70px;
      //background-color: red;
      box-sizing: border-box;
      display: flex;
      //flex-direction: column;
      justify-content: space-between;
      align-items: flex-end;
      padding: 0 20px;
      padding-bottom: 20px;
      font-size: 16px;
      border-bottom: 1px solid #ccc;
      position: relative;
      user-select: none;

      .more-btn {
        position: relative;
        color: rgb(107, 107, 107);
        bottom: -10px;
        width: 30px;
        height: 30px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 5px;
        cursor: pointer;
        right: -8px;
        font-size: 20px;
      }

      .more-btn:hover {
        background-color: rgb(224, 224, 224);
      }
    }

    .main-container {
      flex: 1;
      display: flex;
      flex-direction: column;
      position: relative;
      min-height: 0;
      /* 防止父级出现滚动条 */
      overflow: hidden;
      /* 确保父级不会滚动 */
    }

    .drawer-active {
      width: 250px;
    }

    .drawer-dis {
      width: 0;
    }

    .drawer {
      right: 0;
      position: absolute;
      height: 100%;
      overflow: hidden;
      background-color: white;
      z-index: 1;
      transition: 0.3s;
      outline: none;

      .drawer-inner {
        min-width: 250px;
        padding: 15px;


        .drawer-header {
          display: grid;
          grid-template-columns: 1fr 1fr 1fr 1fr;


          li {
            display: flex;
            flex-direction: column;
            align-items: center;
          }

          .title {
            color: rgb(183, 183, 183);
            font-size: 12px;
            margin: 5px 0;
          }
        }



        .drawer-body li:nth-child(3) {
          border-top: 0;
          padding-top: 0;
        }

        .drawer-body {
          margin-top: 10px;

          li {
            border-top: 1px rgb(232, 232, 232) solid;
            padding: 15px 0;
            font-size: 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;



          }

          .clear {
            display: flex;
            justify-content: center;
            color: red;
            cursor: pointer;
          }

        }
      }
    }

    .message-list-wrapper {
      flex: 1;
      /* 自动填充剩余空间 */
      overflow: hidden;
      min-height: 0;
      /* 允许flex子项收缩 */
    }

    .chat-message-list-container {
      padding: 20px;
      height: 100%;
    }

    .resize-handle-horizontal {
      height: 6px;
      width: 100%;
      background-color: transparent;
      cursor: row-resize;
      flex-shrink: 0;
      position: relative;
      display: flex;
      align-items: center;

      &::before {
        content: '';
        width: 100%;
        height: 1px;
        background-color: #dfdfdf;
      }

      &:hover::before {
        background-color: #bbb;
      }

      &:active::before {
        background-color: #999;
      }
    }

    .message-input-container {
      display: flex;
      flex-direction: column;
      flex-shrink: 0;
      /* 防止被压缩，保持设定的高度 */
    }

  }

}
</style>
